from typing import List
from fastapi import Depends, HTTPException, Request, status
from app.models.user import User, UserRole
from app.schemas.user import UserOccupied

async def get_current_user(request: Request) -> UserOccupied:
    """
    获取当前认证用户
    
    Args:
        request: FastAPI请求对象
        
    Returns:
        返回当前认证的用户信息
        
    Raises:
        HTTPException: 如果用户未认证则抛出401错误
    """
    user = request.state.user
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户未认证",
            headers={"WWW-Authenticate": "Bearer"}
        )
    return user

def require_role(required_roles: List[UserRole]):
    """
    角色权限检查装饰器
    
    Args:
        required_roles: 允许访问的角色列表
        
    Returns:
        返回一个权限检查函数
    """
    def role_checker(request: Request):
        """
        检查用户角色权限
        
        Args:
            request: FastAPI请求对象
            
        Raises:
            HTTPException: 
                - 401: 如果用户未认证
                - 403: 如果用户权限不足
        """
        user = getattr(request.state, "user", None)
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户未认证",
                headers={"WWW-Authenticate": "Bearer"}
            )
            
        # 检查用户角色是否在允许的角色列表中
        if user.role not in required_roles:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="权限不足"
            )
    return role_checker

if __name__ == '__main__':
    pass
